package gu.sql2java.excel.json;

import java.util.concurrent.TimeUnit;

import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.gitee.l0km.aocache.annotations.AoWeakCacheable;
import com.google.common.base.Throwables;

/**
 * JSON类型字段使用jJackson自定义反序列化器实现的数据导入适配器实现
 * @author guyadong
 * @since 3.29.0
 */
@SuppressWarnings("rawtypes")
public class JacksonDeserializeHandler extends BaseJsonDeserializeHandler<JsonDeserializer> {
	public JacksonDeserializeHandler() {
		super();
	}
	public <T>JacksonDeserializeHandler(JsonDeserializer<T> initDeserializer, Class<T> initType, T initEmptyValue) {
		super(initDeserializer, initType, initEmptyValue);
	}
	@SuppressWarnings("unchecked")
	@AoWeakCacheable(maximumSize = 200, expireAfterAccess = 60, expireAfterAccessTimeUnit = TimeUnit.SECONDS)
	private static ObjectMapper objectMapperOf(JsonDeserializer deserializer, Class<?> type) {
		try {
			ObjectMapper mapper = new ObjectMapper();
			// 通过simpleModule进行注册
			SimpleModule simpleModule = new SimpleModule();
			simpleModule.addDeserializer(type, deserializer);
			// 注册simpleModule
			mapper.registerModule(simpleModule);
			return mapper;
		} catch (Exception e) {
			Throwables.throwIfUnchecked(e);
			throw new RuntimeException(e);
		}
	}
	@SuppressWarnings({ "unchecked" })
	protected Object deserialize(String value,JsonDeserializer deserializer,Class type) {
		 try {
			return objectMapperOf(deserializer, type).readValue(value,type);
		} catch (Exception e) {
			Throwables.throwIfUnchecked(e);
			throw new RuntimeException(e);
		} 
	}
}
